package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"path"
	"path/filepath"
	"strings"

	"github.com/odigos-io/odigos/cli/cmd"
	"github.com/spf13/cobra/doc"
)

const fmTemplate = `---
title: "%s"
sidebarTitle: "%s"
---
`

func main() {
	filePrepender := func(filename string) string {
		name := filepath.Base(filename)
		base := strings.TrimSuffix(name, path.Ext(name))
		command := strings.Replace(base, "_", " ", -1)
		return fmt.Sprintf(fmTemplate, command, command)
	}

	linkHandler := func(name string) string {
		base := strings.TrimSuffix(name, path.Ext(name))
		return "/cli/" + strings.ToLower(base)
	}

	rootCmd := cmd.RootCmd()
	outputDir := "../../docs/cli"

	err := doc.GenMarkdownTreeCustom(&rootCmd, outputDir, filePrepender, linkHandler)
	if err != nil {
		log.Fatal(err)
	}

	// Post-process files to remove the watermark
	files, err := filepath.Glob(filepath.Join(outputDir, "*.md"))
	if err != nil {
		log.Fatal(err)
	}

	watermark := "###### Auto generated by spf13/cobra"
	for _, file := range files {
		content, err := ioutil.ReadFile(file)
		if err != nil {
			log.Printf("Error reading file %s: %v", file, err)
			continue
		}

		updatedContent := strings.Split(string(content), watermark)[0] // Remove everything after the watermark
		err = ioutil.WriteFile(file, []byte(strings.TrimSpace(updatedContent)), 0644)
		if err != nil {
			log.Printf("Error writing file %s: %v", file, err)
		}
	}
}
